package com.iqiyi.pps.epg.core.utils;

import com.alibaba.fastjson.JSONObject;
import com.iqiyi.kiwi.utils.HttpClientConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by karkarrotxu on 2014/11/21.
 */
public final class IpUtils {
    private static Logger logger = LoggerFactory.getLogger(IpUtils.class);
    public static final String IP_QUERY_URL = "http://ip.geo.iqiyi.com/cityjson?ip=@&format=json";
    public static final int TIME_OUT = 5000;
    public static final int LOOP = 3;
    public static final int RESPONSE_STATUS = 200;
    public static final String CHINA =  "中国大陆";
    private IpUtils(){};
    public enum IPLocation {
        code,data,ip,isp,country,province,city,isp_id,country_id,province_id,city_id,location_id
    }

    public static JSONObject getNetwork(String ip , int timeOut){
        JSONObject data = new JSONObject();
        String URL =IP_QUERY_URL.replace("@",ip);
        for (int i = 0; i < LOOP; i++) {
            HttpClientConnection hcc = new HttpClientConnection(URL, HttpClientConnection.GET_METHOD);
            hcc.setSoTimeout(timeOut);
            hcc.connect();
            if (hcc.getStatus() == RESPONSE_STATUS) {
                JSONObject jsonObject = JSONObject.parseObject(hcc.getBody());
                if (jsonObject.getString("code").equals("A00000")) {
                    data = jsonObject.getJSONObject("data");
                    break;
                }
            }
        }
        return data;
    }

    public static JSONObject getNetwork(String ip) {
        return getNetwork(ip,TIME_OUT);
    }
}
